package com.freemalll.merchant.service.impl.coopManagement;


import cn.hutool.core.convert.Convert;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.freemalll.common.core.exception.BusinessException;
import com.freemalll.merchant.common.CommonEnum;
import com.freemalll.merchant.domain.dto.coopManagement.AssetManageDetailEditDto;
import com.freemalll.merchant.domain.vo.coopManagement.AssetManageDetailsVo;
import com.freemalll.merchant.domain.entity.coopManagement.MerAssetLog;
import com.freemalll.merchant.domain.entity.coopManagement.MerAssetManageDetail;
import com.freemalll.merchant.service.coopManagement.MerAssetLogService;
import com.freemalll.merchant.service.coopManagement.MerAssetManageDetailService;
import com.freemalll.merchant.mapper.coopManagement.MerAssetManagementDetailMapper;
import com.freemalll.merchant.utils.DtoDiffUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 服务层实现。
 *
 * @author songshixiong
 * @since 2025-04-29
 */
@Slf4j
@Service
@Transactional(rollbackFor = Exception.class)
public class MerAssetManageDetailServiceImpl extends ServiceImpl<MerAssetManagementDetailMapper, MerAssetManageDetail> implements MerAssetManageDetailService {

    @Resource
    private MerAssetLogService merAssetLogService;


    @Override
    public void editBatch(List<AssetManageDetailEditDto> details, String sourceId) {
        if (CollectionUtils.isEmpty(details) || !StringUtils.hasText(sourceId)) {
            log.info("------------------ 批量修改资方明细参数为空 ------------------");
            return;
        }
        for (AssetManageDetailEditDto detail : details) {
            //判断区间字段大小问题
            if (detail.getMonthlyLimit() != null && detail.getDailyLimit() != null && detail.getMonthlyLimit().compareTo(detail.getDailyLimit()) < 0) {
                throw BusinessException.businessOther("月限额错误，月限额必须大于等于日限额");
            }

            if (detail.getHighestRate().compareTo(detail.getMinimumRate()) < 0) {
                throw BusinessException.businessOther("费率区间错误，最高费率必须大于等于最低费率");
            }
            if (detail.getHighestAge() < detail.getMinimumAge()) {
                throw BusinessException.businessOther("年龄区间错误，最高年龄必须大于等于最低年龄");
            }
            if (detail.getMaximumAmount().compareTo(detail.getMinimumAmount()) < 0) {
                throw BusinessException.businessOther("授信区间错误，最高金额必须大于等于最低金额");
            }
        }

        //将页面未传的场景明细设置为禁用
        List<MerAssetManageDetail> list = baseMapper.selectList(Wrappers.<MerAssetManageDetail>lambdaQuery().eq(MerAssetManageDetail::getSourceId, sourceId).eq(MerAssetManageDetail::getEnableFlag, 1));
        if (!CollectionUtils.isEmpty(list)) {
            List<AssetManageDetailEditDto> temp = details.stream().filter(d -> StringUtils.hasText(d.getSourceDetailId())).collect(Collectors.toList());
            List<String> sourceDetailIds = temp.stream().map(AssetManageDetailEditDto::getSourceDetailId).collect(Collectors.toList());
            List<MerAssetManageDetail> diffList = list.stream().filter(detail -> !sourceDetailIds.contains(detail.getSourceDetailId())).collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(diffList)) {
                for (MerAssetManageDetail detail : diffList) {
                    detail.setEnableFlag(0);
                    baseMapper.updateById(detail);
                }
            }
        }
        for (AssetManageDetailEditDto detail : details) {
            //主键为空则新增
            if (StringUtils.hasText(detail.getSourceDetailId())) {
                //修改
                MerAssetManageDetail managementDetail = baseMapper.selectById(detail.getSourceDetailId());
                if (managementDetail == null) {
                    continue;
                }
                detail.init();
                AssetManageDetailEditDto temp = new AssetManageDetailEditDto();
                BeanUtils.copyProperties(managementDetail, temp);
                temp.init();
                String changedFields = DtoDiffUtil.getChangedFields(temp, detail);
                BeanUtils.copyProperties(detail, managementDetail);
                baseMapper.updateById(managementDetail);
                if (StringUtils.hasText(changedFields)) {
                    MerAssetLog log = new MerAssetLog();
                    log.setRelationId(managementDetail.getSourceDetailId());
                    log.setLogDesc(changedFields);
                    log.setOperationType(CommonEnum.merchantAssetLogType.EDIT.name());
                    merAssetLogService.save(log);
                }
            } else {
                MerAssetManageDetail merAssetManageDetail = Convert.convert(MerAssetManageDetail.class, detail);
                merAssetManageDetail.setSourceId(sourceId);
                baseMapper.insert(merAssetManageDetail);
                MerAssetLog log = new MerAssetLog();
                log.setRelationId(merAssetManageDetail.getSourceDetailId());
                log.setLogDesc(CommonEnum.merchantAssetLogType.ADD.getDescription());
                log.setOperationType(CommonEnum.merchantAssetLogType.ADD.name());
                merAssetLogService.save(log);
            }
        }
    }

    @Override
    public List<AssetManageDetailsVo> selectDetails(String sourceId) {
        return baseMapper.selectDetails(sourceId);
    }
}
